package com.tianyi.controller;

import com.tianyi.fileUpload.FileUploadService;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 *
 * @author cuixuhui
 */
@RestController
@RequestMapping("/test")
public class TestController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${project.env}")
    String env;

    @RequestMapping("/env")
    public String env(){

        return env;
    }

    @RequestMapping("/hi")
    public String hello(){
        logger.info("asdfg={}","gfdsa");
        return "hello";
    }

    @RequestMapping("/mapper")
    public String mapper(){

        return "hello";
    }

    @Autowired
    private FileUploadService fileUploadService;

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file) {

        if (true){
            fileUploadService.uploadPhotoWithThumbnails(file);
            return "success";
        }

        if (file == null || file.isEmpty()){
            return "file is null";
        }
        String path = "/Users/cuixuhui/Downloads/ph2/";
        UUID uuid = UUID.randomUUID();
        String originalFilename = file.getOriginalFilename();
        String uuidStr = uuid.toString();
        String fileName = uuidStr + "_" + originalFilename;

        String mark = File.separator+"tmp"+File.separator;
        //原文件
        File dest = new File(path + fileName);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            InputStream inputStream = file.getInputStream();
            Thumbnails.Builder<? extends InputStream> of = Thumbnails.of(inputStream);
            //保存原文件
            file.transferTo(dest);
            //保存缩略图
            of.size(200, 300).keepAspectRatio(false).toFile(path+mark+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
